package com.zbest.zpay.shared.process;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Repository;

import com.zbest.common.lang.enums.BizCode;
import com.zbest.common.lang.exception.ZpayException;
import com.zbest.component.framework.pigeon.template.Action;
import com.zbest.component.framework.pigeon.template.Template;
import com.zbest.component.framework.pigeon.template.TemplateManager;

@Repository("processTemplate")
public class ProcessTemplate implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void process(String flow, Map<String, Object> requestData, ProcessResult processResponse) {

        excuteProcess(flow, null, requestData, processResponse);
    }

    public void process(String flow, String processName, Map<String, Object> requestData,
                        ProcessResult processResponse) {

        excuteProcess(flow, processName, requestData, processResponse);
    }

    private void excuteProcess(String flow, String processName, Map<String, Object> requestData,
                               ProcessResult processResponse) {

        if (StringUtils.isBlank(flow)) {
            throw new ZpayException(BizCode.NO_PROCESS_MATCHED);
        }

        TemplateManager templateManager = (TemplateManager) this.applicationContext
            .getBean("webTemplateManager");
        Template template = templateManager.getTemplateByName(flow);
        if (null != template) {
            if (StringUtils.isBlank(processName)) {
                // 没有提供处理类型，则取默认的处理类型先处理
                processName = "default";
            }
            com.zbest.component.framework.pigeon.template.Process process = template
                .getProcessMap().get(processName);
            if (null != process && !process.getActionList().isEmpty()) {
                try {
                    ActionContext.getContext().setRequest(requestData);
                    // 请求和响应放入线程.
                    for (Action action : process.getActionList()) {
                        BaseAction baseAction = (BaseAction) action.getBean();
                        baseAction.perform(processResponse);
                        if (ActionContext.getContext().isEnd()) {
                            break;
                        }
                    }
                } finally {
                    ActionContext.removeContext();
                }
            } else {
                throw new ZpayException(BizCode.NO_PROCESS_MATCHED);
            }
        } else {
            throw new ZpayException(BizCode.NO_PROCESS_MATCHED);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
